package com.dily.study.demo.thread;

/**
 * Date: 2022-08-10 星期三
 * Time: 10:32
 * Author: Dily_Su
 * Remark:
 * 买票 方法加锁(隐式锁)
 */
public class UnSafeBuyTicket{


    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"苦逼的我").start();
        new Thread(buyTicket,"牛逼的你们").start();
        new Thread(buyTicket,"可恶的黄牛").start();

    }
}

class  BuyTicket  implements Runnable{
    private int ticketNums = 10;
    boolean flag = true;

    @Override
    public void run() {

        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void  buy() throws InterruptedException {

        if (ticketNums <= 0 ){
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+"买了第"+ ticketNums-- +"张票");
        Thread.sleep(100);
    }

}
